const express = require('express');
const cors = require('cors');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 模拟数据库
let posts = [
    { id: 1, title: 'First Post', content: 'Hello World!', author: 'Admin', createdAt: new Date() },
    { id: 2, title: 'Second Post', content: 'Jenkins CI/CD is awesome!', author: 'DevOps', createdAt: new Date() }
];

// 健康检查
app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        timestamp: new Date().toISOString(),
        version: process.env.VERSION || '1.0.0',
        environment: process.env.NODE_ENV || 'development'
    });
});

// 获取所有文章
app.get('/api/posts', (req, res) => {
    res.json({
        success: true,
        data: posts,
        count: posts.length
    });
});

// 获取单篇文章
app.get('/api/posts/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const post = posts.find(p => p.id === id);

    if (!post) {
        return res.status(404).json({
            success: false,
            message: 'Post not found'
        });
    }

    res.json({
        success: true,
        data: post
    });
});

// 创建文章
app.post('/api/posts', (req, res) => {
    const { title, content, author } = req.body;

    if (!title || !content || !author) {
        return res.status(400).json({
            success: false,
            message: 'Title, content, and author are required'
        });
    }

    const newPost = {
        id: posts.length + 1,
        title,
        content,
        author,
        createdAt: new Date()
    };

    posts.push(newPost);

    res.status(201).json({
        success: true,
        data: newPost,
        message: 'Post created successfully'
    });
});

// 更新文章
app.put('/api/posts/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const postIndex = posts.findIndex(p => p.id === id);

    if (postIndex === -1) {
        return res.status(404).json({
            success: false,
            message: 'Post not found'
        });
    }

    const { title, content, author } = req.body;

    posts[postIndex] = {
        ...posts[postIndex],
        title: title || posts[postIndex].title,
        content: content || posts[postIndex].content,
        author: author || posts[postIndex].author,
        updatedAt: new Date()
    };

    res.json({
        success: true,
        data: posts[postIndex],
        message: 'Post updated successfully'
    });
});

// 删除文章
app.delete('/api/posts/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const postIndex = posts.findIndex(p => p.id === id);

    if (postIndex === -1) {
        return res.status(404).json({
            success: false,
            message: 'Post not found'
        });
    }

    posts.splice(postIndex, 1);

    res.json({
        success: true,
        message: 'Post deleted successfully'
    });
});

// 404 处理
app.use((req, res) => {
    res.status(404).json({
        success: false,
        message: 'Route not found'
    });
});

// 错误处理
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        success: false,
        message: 'Internal server error'
    });
});

module.exports = app;
